package com.zhaofujun.filequeue;


import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public final class FileQueueFactory {
    private static final Map<String, FileQueue<?>> fileQueueMap = new ConcurrentHashMap<>();

    public static <U> FileQueue<U> createFileQueue(String basePath, int elementSize, Serializer<U> serializer, DeleteSegmentStrategy deleteSegmentStrategy) throws IOException {
        FileQueue<U> fileQueue = new FileQueueWithReactor<>(basePath, elementSize, deleteSegmentStrategy, serializer, () -> removeFileQueue(basePath));
        fileQueueMap.put(basePath, fileQueue);
        return fileQueue;
    }

    public static <U> FileQueue<U> createFileQueue(String basePath, int elementSize, Serializer<U> serializer) throws IOException {
        FileQueue<U> fileQueue = new FileQueueWithReactor<>(basePath, elementSize, new PeriodDeleteSegmentStrategy(1, TimeUnit.HOURS), serializer, () -> removeFileQueue(basePath));
        fileQueueMap.put(basePath, fileQueue);
        return fileQueue;
    }

    public static <U> FileQueue<U> load(String basePath) throws IOException {
        FileQueue<U> fileQueue = (FileQueue<U>) fileQueueMap.get(basePath);
        if (fileQueue == null) {
            throw new IOException("file queue not found");
        }
        return fileQueue;
    }

    private static void removeFileQueue(String basePath) {
        fileQueueMap.remove(basePath);
    }
}
